package com.groot.medical.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.groot.common.controller.BaseServletController;
import com.groot.medical.entity.Menu;
import com.groot.medical.entity.MenuTreeDto;
import com.groot.medical.entity.Role;
import com.groot.medical.entity.SysUser;
import com.groot.medical.entity.Ztree;
import com.groot.medical.service.MenuService;
import com.groot.medical.service.MenuServiceImpl;
import com.groot.medical.service.RoleService;
import com.groot.medical.service.RoleServiceImpl;

@WebServlet("/sys/role.do")
public class RoleController extends BaseServletController {
	
	private RoleService roleService = new RoleServiceImpl();
	private MenuService menuService = new MenuServiceImpl();
	private static final long serialVersionUID = 1L;
	/*private UserService userService = new UserServiceImpl();*/
	
	
	private static Logger LOGGER = Logger.getLogger(LoginController.class);
	
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOGGER.info("this is @WebServlet(\"/index.do\").execute()");
		return null;
	}
	/**
	 * 查询所有角色信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findAllRoleInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tgId = request.getParameter("tgId"); 
		System.out.println("tgId是多少啊啊啊啊"+tgId);
		List<Role> roleList = roleService.findAllRoleList();
		request.setAttribute("roleList", roleList);
		List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
		System.out.println("大哥啊"+menus);
		List<Menu> result = new ArrayList<Menu>();
		/*根据页面传过来的id与该用户所有权限的上一级id比较
		 * 若该权限的上一级传过来的id相同则存入新集合
		 */
		for(Menu menu: menus){
			if(menu.getMenuPid().equals(tgId)){
				result.add(menu);
			}
		}
		System.out.println("result我要他的："+result);
		Gson gson = new Gson();
		request.setAttribute("resultMenus", gson.toJson(result));
		request.setAttribute("tgId", tgId);	
		return "/WEB-INF/page/role/role_list.jsp";
	
	}
	
	/**
	 * 添加角色信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	/*public String addRole(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String roleid = request.getParameter("roleid");
		String rolename = request.getParameter("rolename");
		String roledescribe = request.getParameter("roledescribe");
		Role role = new Role();
		role.setRoleId(roleid);
		role.setRoleName(rolename);
		role.setRoleDescribe(roledescribe);
		
		int i  = roleService.addRole(role);
		
		return null;
	}*/
	/**
	 * 打开添加角色页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String openAddRole (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Menu> menuList = new ArrayList<>();
		String tgId = request.getParameter("tgId");
		menuList=menuService.findAllMenuLsit();
		List<Ztree> ztrees = new ArrayList<>();
		for (int i = 0; i < menuList.size(); i++) {
			Ztree ztree = new Ztree();
			Menu menu = menuList.get(i);
			ztree.setId(menu.getMenuId());
			ztree.setpId(menu.getMenuPid());
			ztree.setName(menu.getMenuName());
		
			ztrees.add(ztree);
		}
		Gson gson = new Gson();
		String json = gson.toJson(ztrees);
		request.setAttribute("menuList", json);
		request.setAttribute("tgId", tgId);
		
		    
		return "/WEB-INF/page/role/addrole.jsp";
	}
	/**
	 * 给于角色权限
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String giveMenuToRole (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String[] menuIds = request.getParameterValues("menuIds");
		String roleid = request.getParameter("roleid");
		String rolename = request.getParameter("rolename");
		String roledescribe = request.getParameter("roledescribe");
		String tgId = request.getParameter("tgId");
		Role role = new Role();
		role.setRoleId(roleid);
		role.setRoleName(rolename);
		role.setRoleDescribe(roledescribe);
		
		int n  = roleService.addRole(role,menuIds);
		
		
		return findAllRoleInfo(request,response);
	}
	/**
	 * 打开修改角色页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String openEditRole (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tgId=request.getParameter("tgId");
		String roleid = request.getParameter("roleid");
		//查询角色信息
		Role role = roleService.findRoleByRoleId(roleid);
		//查询当前角色已经拥有的权限
		List<Menu> roleHasMenu = menuService.findMenuByRoleId(roleid);
		//查询所有权限信息
		List<Menu> menuList=menuService.findAllMenuLsit();
		//权限比对
		List<Ztree> ztrees = new ArrayList<>();
		for (int i = 0; i < menuList.size(); i++) {
			Ztree ztree = new Ztree();
			Menu menu = menuList.get(i);
			ztree.setId(menu.getMenuId());
			ztree.setpId(menu.getMenuPid());
			ztree.setName(menu.getMenuName());
			for(Menu menu1 :roleHasMenu){
				if(menu.getMenuId().equals(menu1.getMenuId())){
					ztree.setChecked(true);
					break;
				}
				
			}
			ztrees.add(ztree);
		}
		Gson gson = new Gson();
		String json = gson.toJson(ztrees);
		request.setAttribute("tgId", tgId);
		request.setAttribute("role", role);
		request.setAttribute("menuList", json);
		
		
		System.out.println("查询当前角色已经拥有的权限:"+roleHasMenu);
		return "/WEB-INF/page/role/editrole.jsp";
	
	}
	/**
	 * 修改角色信息（包括其拥有权限）
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String editRoleInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String roleid=request.getParameter("roleid");
		String rolename=request.getParameter("rolename");
		String roledescribe=request.getParameter("roledescribe");
		String tgId=request.getParameter("tgId");
		String [] menuIds = request.getParameterValues("menuIds");
		Role role = new Role();
		role.setRoleId(roleid);
		role.setRoleName(rolename);
		role.setRoleDescribe(roledescribe);
		
		for(int i=0;i<menuIds.length;i++){
			System.out.println(menuIds[i]);
		}
		/*//先查询当先角色是否拥有权限
		List<Menu> roleHasMenu = menuService.findMenuByRoleId(roleid);*/
		
		//先删除该角色当前拥有权限
		int del = menuService.delMenuByRoleId(roleid);
		System.out.println("先删除该角色当前拥有权限"+del);
		
		//再将重新勾选的权限添加
			int n  = roleService.addMenuToRole(role,menuIds);
			if(n==1){
				request.setAttribute("flag", "<script type='text/javascript'>alert('角色修改成功！');</script>");
				request.setAttribute("tgId", tgId);
			}
			else{
				request.setAttribute("flag", "<script type='text/javascript'>alert('角色修改失败！');</script>");
			}

		return findAllRoleInfo(request,response);
	}
	
	/**
	 * 删除角色信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public void deleteRole(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String tgId = request.getParameter("tgId");
		String resultString = "false";
		//判断该角色是否已经分配给用户
		int i = roleService.checkRoleHad(id);
		System.out.println("大概有几条："+i);
		if(i>0){
			resultString = "false";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}else{
			//删除角色(以及该角色拥有的权限)
			int flag = roleService.deleteRoleById(id);
			if(flag>0){
				resultString = "true";
				response.setContentType("text/html");
		        ServletOutputStream outputStream = response.getOutputStream();
		        outputStream.write(resultString.getBytes());
		        outputStream.close();
			}else{
				resultString = "false";
				response.setContentType("text/html");
		        ServletOutputStream outputStream = response.getOutputStream();
		        outputStream.write(resultString.getBytes());
		        outputStream.close();
			}
			
		}
		

	}
	
	

}
